package com.yunche.yunchebusiness.ui.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseItemDraggableAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener
import com.yunche.yunchebusiness.R
import com.yunche.yunchebusiness.base.BaseApp.Companion.mContext
import com.yunche.yunchebusiness.base.BaseFragment
import com.yunche.yunchebusiness.base.rx.SchedulerUtils
import com.yunche.yunchebusiness.common.CommonDialog
import com.yunche.yunchebusiness.common.Constant
import com.yunche.yunchebusiness.entity.EvaluateInfo
import com.yunche.yunchebusiness.entity.EvaluateRecord
import com.yunche.yunchebusiness.network.RetrofitManager
import com.yunche.yunchebusiness.network.exception.ErrorStatus
import com.yunche.yunchebusiness.network.exception.ExceptionHandle
import com.yunche.yunchebusiness.ui.activity.evaluate.EvaluateActivity
import com.yunche.yunchebusiness.ui.view.YuncheToolBar
import com.yunche.yunchebusiness.utils.ToastyUtils
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_evaluate.*


/**
 * Create by Crcker on 2018/12/20 11:25
 * Email: Crcker@163.com
 */

@SuppressLint("StaticFieldLeak")

class EvaluateFragment : BaseFragment(), BaseQuickAdapter.OnItemClickListener {
    private var compositeDisposable = CompositeDisposable()

    var disposable: Disposable? = null
    override fun setLayout(): Int = R.layout.fragment_evaluate
    var mAdapter: EvaluateAdapter? = null

    override fun initView() {
        rv_evaluate_record.layoutManager = LinearLayoutManager(activity!!, LinearLayoutManager.VERTICAL, false)
        toolbar.yuncheToolbarCallBack = object : YuncheToolBar.YuncheToolbarCallBack {
            override fun onBackClick() {
            }

            override fun onRightClick() {
                openActivityForResult(EvaluateActivity::class.java, null, 0)
            }
        }

        var swipeMenuCreator = SwipeMenuCreator { leftMenu, rightMenu, position ->
            val height = ViewGroup.LayoutParams.MATCH_PARENT
            val width = resources.getDimensionPixelSize(R.dimen.dp_72)
            var deleteItem = SwipeMenuItem(mContext)
            deleteItem.text = "删除"
            deleteItem.textSize = 14
            deleteItem.setTextColor(Color.WHITE)
            deleteItem.width = width
            deleteItem.height = height
            deleteItem.setBackgroundColor(Color.parseColor("#ef5350"))
            rightMenu.addMenuItem(deleteItem)
        }

        var mMenuItemClickListener = SwipeMenuItemClickListener { menuBridge, position ->
            menuBridge.closeMenu()
            var datas = mAdapter?.data as List<EvaluateRecord>

            deleteRecord(datas[position].id)
        }

        rv_evaluate_record.setSwipeMenuCreator(swipeMenuCreator)
        rv_evaluate_record.setSwipeMenuItemClickListener(mMenuItemClickListener)

        srflay_evaluate_record.setOnRefreshListener {
            initData()
        }
        msv_evaluate_record.setOnRetryClickListener {
            initData()
        }
        rv_evaluate_record.setSwipeItemClickListener { itemView, position ->
            var datas = mAdapter?.data as List<EvaluateRecord>
            var bundle = Bundle()

            var evaluateInfo = EvaluateInfo(
                datas[position].bandCode!!,
                datas[position].buyCarDate,
                datas[position].cityName,
                0f,
                datas[position].mileage,
                0f,
                datas[position].modelCode!!,
                datas[position].seriesCode!!,
                datas[position].modelsName!!,
                datas[position].brandName!!,
                datas[position].id,
                datas[position].seriesName,
                datas[position].carIcon
            )

            bundle.putSerializable("evaluateInfo", evaluateInfo)
            openActivityForResult(EvaluateActivity::class.java, bundle, 0)
        }
    }

    private fun showLoading() {
        msv_evaluate_record.showLoading()
    }

    private fun hideLoading() {
        srflay_evaluate_record.isRefreshing = false
    }

    private fun showError(msg: String) {
        ToastyUtils.showError(msg)
        msv_evaluate_record.showError(msg)
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

    }

    private fun deleteRecord(id: Int) {
        CommonDialog.showLoading(activity!!, "正在删除")
        disposable = RetrofitManager.service.deleteEvaluate(id).compose(SchedulerUtils.ioToMain())
            .subscribe({
                CommonDialog.cancle()
                if (it.resultCode == ErrorStatus.SUCCESS) {
                    initData()
                } else {
                    showError(it.message!!)
                }
            }, {
                CommonDialog.cancle()
                showError(ExceptionHandle.handleException(it))
            })

        compositeDisposable.add(disposable!!)
    }

    override fun initData() {
        showLoading()
        disposable = RetrofitManager.service.getEvaluateRecord().compose(SchedulerUtils.ioToMain())
            .subscribe({
                hideLoading()
                if (it.resultCode == ErrorStatus.SUCCESS) {
                    if (it.datas!!.isEmpty()) {
                        msv_evaluate_record.showEmpty("当前没有估价记录")
                    } else {
                        mAdapter = EvaluateAdapter(R.layout.evaluate_record_item, it.datas!!)
                        mAdapter!!.onItemClickListener = this
                        rv_evaluate_record.adapter = mAdapter
                        msv_evaluate_record.showContent()
                    }
                } else {
                    showError(it.message!!)
                }
            }, {
                hideLoading()
                showError(ExceptionHandle.handleException(it))
            })

        compositeDisposable.add(disposable!!)

    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            initData()
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Constant.REFRESH_DATA) {
            initData()
        }
    }

    inner class EvaluateAdapter constructor(id: Int, data: List<EvaluateRecord>) :
        BaseItemDraggableAdapter<EvaluateRecord, BaseViewHolder>(id, data) {

        override fun convert(helper: BaseViewHolder?, item: EvaluateRecord?) {
            helper?.setText(R.id.tv_brand_name, item?.brandName + "-" + item?.seriesName)
            helper?.setText(R.id.tv_series_name, item?.modelsName)
            helper?.setText(R.id.tv_evaluate_price, "${item?.minEvaluate} - ${item?.maxEvaluate}")
            Glide.with(mContext).load(item?.carIcon).into(helper?.getView(R.id.iv_car_icon)!!)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (disposable!!.isDisposed) {
            disposable?.dispose()
        }
    }

}